﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;

namespace Method.Token
{
    public static class JwtOperating
    {
        /// <summary>
        /// 生成秘钥
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <param name="userId">用户ID</param>
        /// <param name="minute">持续时间</param>
        /// <returns></returns>
        public static string CreateJwt(string sessionId, string UserId)
        {
            System.DateTime utcNow = System.DateTime.UtcNow;
            string key = sessionId;
            SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));

            var claims = new List<Claim>() {
                new Claim("UserId",UserId),
            };
            JwtSecurityToken jwtToken = new JwtSecurityToken(
                issuer: "Article",//生成者
                audience: "WDS",//获取者
                claims: claims,//插入claims的数据
                notBefore: utcNow,//当前时间
                expires: utcNow.AddDays(30),//过期时间
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
            );

            //生成token方式1
            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <param name="token">令牌</param>
        /// <returns></returns>
        public static string SelectJwt(string token,string sessionId)
        {
            //校验token
            var validateParameter = new TokenValidationParameters()
            {
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidateIssuer = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "Article",
                ValidAudience = "WDS",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(sessionId)),
            };

            try
            {
                //校验并解析token
                var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(token, validateParameter, out SecurityToken validatedToken);//validatedToken:解密后的对象
                var jwtPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); //获取payload中的数据 

                return GetJson.getJson(jwtPayload, "UserId");
            }
            catch (SecurityTokenExpiredException)
            {
                //OperResult<string>.Failed("令牌已过期,请重新登录");
                return null;
            }
            catch (SecurityTokenException)
            {
                //OperResult<string>.Failed("令牌错误,请重新登录");
                return null;
            }
        }
    }
}
